// 主页搜索框组件
import style from "./style.module.css";
import { useState } from "react";
import { useHistory } from "react-router-dom";
import cityData from "../../assets/area.json";

interface Area {
  name: string;
  value?: string | undefined;
  parent?: string | undefined;
}

interface Prop {
  city?: string;
  getArea: (area: string) => void | undefined;
}

export default function HomeSearchItem(props: Prop) {
  const [province, setProvince] = useState<Area[]>([]);
  const [city, setCity] = useState<Area[]>([]);
  const [isShow, setIsShow] = useState<Boolean>(false);
  const [state, setState] = useState<Number>(0);
  const history = useHistory();

  const change = () => {
    let pro: Area[] = [];
    let allCity: Area[] = [];
    cityData.forEach((item) => {
      if (item?.parent === undefined) pro.push(item);
      if (item?.value === "100000") allCity = cityData;
    });
    setProvince(pro);
    setCity(allCity);
    setIsShow(!isShow);
  };

  const getCity = (value: string | undefined, index: number) => {
    let city2: Area[] = [];
    cityData.forEach((item) => {
      if (item?.parent === value) {
        city2.push(item);
      }
      if (value === "100000") {
        city2 = cityData;
      }
    });
    setCity(city2);
    setState(index);
  };

  const goSearch = (name: string) => {
    setIsShow(!isShow);
    setTimeout(() => {
      history.push("/search", { area: name });
    }, 1000);
  };

  return (
    <>
      <div className={style.city} onClick={change}>
        <span className={style.leftName}>{props?.city}</span>
        <span className={style.rightIcon}></span>
      </div>
      <div
        className={isShow ? `${style.cityList} ${style.active}` : style.active}
      >
        <div className={style.cityTitle}>
          <span
            className={style.back}
            onClick={() => setIsShow(!isShow)}
          ></span>
          选择城市
        </div>
        <div className={style.province}>
          <ul>
            {province.map((item, index) => {
              return (
                <li
                  className={
                    index === state
                      ? `${style.selected} ${style.proItem}`
                      : style.proItem
                  }
                  key={index}
                  onClick={() => getCity(item.value, index)}
                >
                  {item.name}
                </li>
              );
            })}
          </ul>
        </div>
        <div className={style.provinceChild}>
          <ul>
            {city.map((item, index) => {
              return (
                <li
                  className={style.proItem}
                  key={index}
                  onClick={() => {
                    goSearch(item.name);
                    props.getArea(item.name);
                  }}
                >
                  {item.name}
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    </>
  );
}
